// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Microsoft.WindowsCE.Forms;
using OpenNETCF.Windows.Forms;
using svs.Mobile.BeyondMedia.FeedCore;
using svs.Mobile.BeyondMedia.Objects;
using svs.Mobile.BeyondMedia.Properties;
using svs.Mobile.BeyondMedia.UiCore;

namespace svs.Mobile.BeyondMedia
{
	public partial class FeedProperties : Form
	{
		public Feed CurrentFeed;
		private string m_OldActiveCategory;
		private bool _MustRefreshRepository = false;
		readonly InputPanel _InputPanel;

		public FeedProperties()
		{
			InitializeComponent();
			KeyPreview = true;

			if (PlatformDetection.IsPocketPC())
			{
				_InputPanel = new InputPanel();
				_InputPanel.EnabledChanged += OnInputPanelChanged;
			}
		}

		private void OnInputPanelChanged(object sender, EventArgs e)
		{
			if (_InputPanel.Enabled)
			{
				ExtrasPanel.Height += _InputPanel.Bounds.Height;
				Helpers.EnsureSIPDoesNotOverlapActiveControl(this, _InputPanel.VisibleDesktop.Height);
			}
			else
				ExtrasPanel.Height -= _InputPanel.Bounds.Height;
		}

		public bool MustRefreshRepository
		{
			get { return _MustRefreshRepository; }
		}

		private void menuDone_Click(object sender, EventArgs e)
		{
			DialogResult = DialogResult.OK;
		}

		private void menuCancel_Click(object sender, EventArgs e)
		{
			if (m_OldActiveCategory == Configuration.ActiveFeedCategory.Value)
				DialogResult = DialogResult.Cancel;
			else
				DialogResult = DialogResult.OK; //the active category was renamed or deleted - must refresh!
		}

		private void FeedProperties_Load(object sender, EventArgs e)
		{
			FeedName.Text = CurrentFeed.Name;
			FeedURL.Text = CurrentFeed.FeedUrl;
			FeedDirectory.Text = CurrentFeed.FeedPath;
			MaxCount.Text = CurrentFeed.MaxEnclosures.ToString();
			MaxOld.Text = ((int) CurrentFeed.KeepEnclosuresDuration.TotalDays).ToString();
			AllowAutoDeletions.SelectedIndex = (int) CurrentFeed.AllowAutoTrackDeletions;
			UserName.Text = CurrentFeed.UserName;
			Password.Text = CurrentFeed.Password;
			MaxWhatIsNew.Text = CurrentFeed.NumToIncludeInWhatIsNew.ToString();

			TracksSortOrder.SelectedIndex = (int)CurrentFeed.TrackSortOrder;

			//Check if the feed setting matches teh default setting - assume it is the default
			PlayerIntegration pi = CurrentFeed.FeedPlayer;
			PlayerSelector.SelectedIndex = (int)pi + 1;

			forceUniqueNames.Checked = CurrentFeed.ForceUniqueTrackNames;
			ForceContentSort.Checked = CurrentFeed.ForceFeedItemSort;

			BindCategories();

			//When creating new feeds default to the current category
			if (String.IsNullOrEmpty(CurrentFeed.Name) && Configuration.ActiveFeedCategory != CategoryManager.AllFeeds)
			{
				Category1.SelectedItem = Configuration.ActiveFeedCategory;
			}

			IncludeInCustomUpdate.Checked = CurrentFeed.IncludeInOneStepDownload;
			OnIncludeInUpdateCheckStateChanged(null, null);
			MaxDownload.Text = CurrentFeed.MaxEnclosuresToOneStepDownload.ToString();

			LongNameHandling.SelectedIndex = CurrentFeed.LeftTruncateLongTrackNames ? 1 : 0;

			FeedURL.Focus();

			m_OldActiveCategory = Configuration.ActiveFeedCategory.Value;

#if  Smartphone
			InputModeEditor.SetInputMode(MaxCount, InputMode.Numeric);
			InputModeEditor.SetInputMode(MaxOld, InputMode.Numeric);
			InputModeEditor.SetInputMode(MaxDownload, InputMode.Numeric);
#endif

			Helpers.EnableFormCutCopyPaste(this);
		}

		private void BindCategories()
		{
			Category1.DataSource = CategoryManager.GetCategoriesForAssignment();
			Category1.DisplayMember = "Name";
			Category1.SelectedItem = CurrentFeed.Categories.Primary;

			Category2.DataSource = CategoryManager.GetCategoriesForAssignment();
			Category2.DisplayMember = "Name";
			Category2.SelectedItem = CurrentFeed.Categories.Secondary;
		}

		private void OnSelectFolder(object sender, EventArgs e)
		{
			FolderBrowserDialog dlg = new FolderBrowserDialog();
			dlg.SelectedPath = string.IsNullOrEmpty(CurrentFeed.FeedPath)?Configuration.EnclosureDownloadPath: CurrentFeed.FeedPath;
			dlg.ShowNewFolderButton = true;
			DialogResult res = dlg.ShowDialog();

			if(res != DialogResult.OK)
				return;

			if (string.Compare(dlg.SelectedPath.Trim(), Configuration.EnclosureDownloadPath, StringComparison.InvariantCultureIgnoreCase) == 0)
			{
				MessageBoxEx.Show(string.Format(Resources.CantUseFeedsRootFolderMessage, Configuration.EnclosureDownloadPath), Resources.CantUseFeedsRootFolderTitle, MessageBoxButtons.OK,
												MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);

				SetFeedFolder.Focus();
				return;
			}

			FeedDirectory.Text = dlg.SelectedPath;
		}

		private const string HTTP = "http://";
		private const string NEWFEED = "New Feed";

		private void OnUrlGotFocus(object sender, EventArgs e)
		{
			if (FeedURL.Text.Length == 0)
			{
				FeedURL.Text = HTTP;
				FeedURL.SelectAll();
			}
		}

		private void OnUrlLostFocus(object sender, EventArgs e)
		{
			if (string.Compare(FeedURL.Text.Trim(), HTTP) == 0)
			{
				FeedURL.Text = String.Empty;
			}
		}

		private void OnMoreClick(object sender, EventArgs e)
		{
			if (ExtrasPanel.Visible)
			{
				ExtrasPanel.Visible = false;
				MoreSettings.Text = "More Settings >>";
			}
			else
			{
				ExtrasPanel.Visible = true;
				MoreSettings.Text = "<< Simple";
				FeedDirectory.Focus();
			}
		}

		private void ManageCategories_Click(object sender, EventArgs e)
		{
			Categories.ShowCategoryEditor();
			BindCategories();
		}

		private void OnIncludeInUpdateCheckStateChanged(object sender, EventArgs e)
		{
			MaxDownload.Enabled = IncludeInCustomUpdate.Checked;
		}

		private void OnNameGotFocus(object sender, EventArgs e)
		{
			if (FeedName.Text.Length == 0)
			{
				FeedName.Text = NEWFEED;
				FeedName.SelectAll();
			}
		}

		private void OnNameLostFocus(object sender, EventArgs e)
		{
			if (string.Compare(FeedName.Text.Trim(), NEWFEED) == 0)
			{
				FeedName.Text = String.Empty;
			}
		}


		private bool CheckAndSaveSettings()
		{
			OnUrlLostFocus(null, null);

			string newUrl = (FeedURL.Text ?? string.Empty).Trim();
			string newName = (FeedName.Text ?? string.Empty).Trim();

			//Check if our feed name was the same as the initial feed url
			bool nameIsUrl =
				!string.IsNullOrEmpty(CurrentFeed.FeedUrl) && string.Compare(CurrentFeed.FeedUrl, newName, StringComparison.InvariantCultureIgnoreCase) == 0;

			//Set the Url
			if (newUrl.Length > 0)
			{
				if (CoreHelper.SafeCreateUri(newUrl) == null)
				{
					MessageBoxEx.Show(Resources.InvalidFeedUrlMsg, Resources.InvalidFeedUrlTitle, MessageBoxButtons.OK,
													MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);

					FeedURL.Focus();
					return false;
				}

				CurrentFeed.FeedUrl = newUrl;
			}
			else
				CurrentFeed.FeedUrl = string.Empty;

			//Set the feed name
			if (nameIsUrl || newName.Length == 0)
			{
				if (!string.IsNullOrEmpty(CurrentFeed.FeedUrl))
				{
					FeedName.Text = CurrentFeed.FeedUrl;
				}
				else
				{
					MessageBoxEx.Show(Resources.FeedNameEmpty, Resources.FeedNameEmptyTitle, MessageBoxButtons.OK,
													MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
					FeedName.Focus();
					return false;
				}
			}

			CurrentFeed.Name = FeedName.Text.Trim();

			string selectedFolder = FeedDirectory.Text.Trim();

			if (CurrentFeed.FeedPath != selectedFolder)
			{
				//Make sure that the folder exists (or it is empty)
				if (!string.IsNullOrEmpty(selectedFolder) && !Directory.Exists(selectedFolder))
				{
					MessageBoxEx.Show(Resources.PodcastDownloadFolderDoesNotExistMsg, Resources.PodcastDownloadFolderDoesNotExistTitle, MessageBoxButtons.OK,
													MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
					SetFeedFolder.Focus();
					return false;
				}

				CurrentFeed.FeedPath = FeedDirectory.Text.Trim();
				_MustRefreshRepository = true;
			}

			CurrentFeed.AllowAutoTrackDeletions = (AllowDeletions)AllowAutoDeletions.SelectedIndex;

			CurrentFeed.Categories.Primary = (FeedCategory)Category1.SelectedItem;
			CurrentFeed.Categories.Secondary = (FeedCategory)Category2.SelectedItem;

			try
			{
				int me = int.Parse(MaxCount.Text);
				if (me <= 0)
					throw new ArgumentException();

				CurrentFeed.MaxEnclosures = me;
			}
			catch
			{
				MessageBoxEx.Show(Resources.MaxCountValidationMsg, Resources.MaxCountValidationTitle, MessageBoxButtons.OK,
												MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
				MaxCount.Focus();
				return false;
			}

			try
			{
				int md = int.Parse(MaxOld.Text);
				if (md <= 0)
					throw new ArgumentException();

				CurrentFeed.KeepEnclosuresDuration = new TimeSpan(md, 0, 0, 0);
			}
			catch
			{
				MessageBoxEx.Show(Resources.MaxOldValidationMsg, Resources.MaxOldValidationTitle, MessageBoxButtons.OK,
												MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
				MaxOld.Focus();
				return false;
			}

			if (IncludeInCustomUpdate.Checked)
			{
				try
				{
					int me = int.Parse(MaxDownload.Text);
					if (me <= 0)
						throw new ArgumentException();

					CurrentFeed.MaxEnclosuresToOneStepDownload = me;
				}
				catch
				{
					MessageBoxEx.Show(Resources.MaxDownloadValidationMsg, Resources.MaxDownloadValidationTitle, MessageBoxButtons.OK,
													MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
					MaxDownload.Focus();
					return false;
				}
			}

			try
			{
				int nwin = int.Parse(MaxWhatIsNew.Text);
				if (nwin < 0)
					throw new ArgumentException();

				CurrentFeed.NumToIncludeInWhatIsNew = nwin;
			}
			catch
			{
				MessageBoxEx.Show(Resources.MaxWhatIsNewValidationMsg, Resources.MaxWhatIsNewValidationTitle, MessageBoxButtons.OK,
												MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
				MaxWhatIsNew.Focus();
				return false;
			}

			CurrentFeed.IncludeInOneStepDownload = IncludeInCustomUpdate.Checked;

			CurrentFeed.ForceUniqueTrackNames = forceUniqueNames.Checked;
			CurrentFeed.ForceFeedItemSort = ForceContentSort.Checked;

			CurrentFeed.TrackSortOrder = (CoreHelper.SortOrder)TracksSortOrder.SelectedIndex;

			CurrentFeed.FeedPlayer = (PlayerIntegration) PlayerSelector.SelectedIndex - 1;

			CurrentFeed.UserName = UserName.Text;
			CurrentFeed.Password = Password.Text;

			CurrentFeed.LeftTruncateLongTrackNames = LongNameHandling.SelectedIndex == 0 ? false : true;

			return true;
		}

		private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if (DialogResult == DialogResult.OK)
			{
				e.Cancel = (CheckAndSaveSettings() == false);
			}
		}

		private void ClearHistory_Click(object sender, EventArgs e)
		{
			CommandManager.CmdMarkClearDownloaded(CurrentFeed, CommandManager.DownloadHistoryOperation.MarkAllPodcastsAsNotDownloaded);
		}

		private void AddToHistory_Click(object sender, EventArgs e)
		{
			CommandManager.CmdMarkClearDownloaded(CurrentFeed, CommandManager.DownloadHistoryOperation.MarkAllPodcastsAsDownloaded);
		}

		protected override void OnKeyDown(KeyEventArgs e)
		{
			switch (e.KeyData)
			{
				case Keys.Up:
				case Keys.Down:
					e.Handled = true;
					SelectNextControl(Helpers.GetFocusedControl(this), e.KeyData == Keys.Down, true, true, true);
					break;

				default:
					break;
			}
		}

	}
}